<?php
namespace App\Models;

use App\Libraries\Decorator\DecoratorInterface\ModelDecorator;
use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
{
    protected $decorators = [];
    protected $rs_format = [
        'code' => 200,
        'data' => []
    ];

    public function addDecorator(ModelDecorator $decorator){
        $this->decorators[] = $decorator;
    }

    public function before(){
        foreach($this->decorators as $decorator){
            $decorator->before();
        }
    }

    public function after(&$data){
        $decorators = array_reverse($this->decorators);
        foreach($decorators as $decorator){
            $data = $decorator->after($data);
        }
        return $data;
    }

    public function scopeWithOnly($query, $relation, Array $columns, Array $where=[])
    {
        return $query->with([$relation => function ($query) use ($columns, $where){
            $query->select($columns);
            foreach($where as $k => $v){
                $query->where($k, $v);
            }
        }]);
    }
}